<?php
	$airmonths = array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	$oldmovie = "";
	$olddir = "";
	$tvxml = "";
	$imdbnr = 0;
	$movtypes = array("mov","avi","mpg","mpeg","divx","ogm","mkv","mp4","m4v","mp4v");
//	$file = "Battlestar.Galactica.S1.E10.The.Hand.of.God.DVDRip.Divx";
//	$file = "heroes.121.hdtv-lol.avi";
//	$file = "Megas XLR - 2x06 Space Booty [Moonsong].avi";



	if(isset($argv[1]) and file_exists($argv[1]) and is_dir($argv[1])){
		processdirectory($argv[1]);
	}else{
		die("\nUsage: php series.php <directory>\n\n");
	}



	function processdirectory($dir){
		global $airmonths, $oldmovie, $movtypes, $tvxml, $olddir, $imdbnr, $argv;
	
		$d = opendir($dir);
		while(false !== ($file = readdir($d))){
			if(substr($file, 0, 1) == "."){ continue; }
			if(is_dir($dir.$file."/")){
				processdirectory($dir.$file."/");
				continue;
			}
			$ext = strtolower(substr($file, strrpos($file, ".")+1));
			if(!in_array($ext, $movtypes)){ echo "Skipping file ".$file."\n"; continue; }
			echo "Processing file ".$file."\n";


			$matches = array();
			if(preg_match("/(.+?)\Ds(\d+)\.?e(\d+?)\D/i", $file, $matches)){
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\Ds(\d+)\.?x(\d+?)\D/i", $file, $matches)){
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)x(\d+)\D/i", $file, $matches)){
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)\D/", $file, $matches)){
				$episode = round(substr($matches[2],1));
				$season  = round(substr($matches[2],0,1));
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(\d+?) - ([\w\s]+) - /", $file, $matches)){
				$episode = round(substr($matches[1],1));
				$season  = 1;
				$title   = str_replace("."," ",$matches[2]);
			}
			$temp = get_show($title,0, $season."x".$episode);

			$title = substr($temp[5],strpos($temp[5], "\"")+1);
			$title = substr($title, 0, strpos($title, "\""));

			$airdate = explode("/",trim(substr($temp[5], strpos($temp[5], "aired on ")+10)));
			$airdate = $airdate[2]."-".array_search($airdate[1],$airmonths)."-".$airdate[0];

			$genres = explode(" | ",trim($temp[10]));

			if(is_array($temp[6])){
				$episodepage = implode("",file($temp[6]));
				$episodeinfo = substr($episodepage, strpos($episodepage, "<td align='center'><font size='2'><b>Episode Summary</b></font></td>"), strpos($episodepage, "<td align='center'><font size='2'><b>Guest Stars</b></font></td>")-strpos($episodepage, "<td align='center'><font size='2'><b>Episode Summary</b></font></td>"));
				$episodeinfo = substr($episodeinfo, strpos($episodeinfo, "<table width='100%'><tr><td>")+strlen("<table width='100%'><tr><td>"));
				$episodeinfo = substr($episodeinfo, 0, strpos($episodeinfo, "</td>"));
				$episodeinfo = strip_tags($episodeinfo);
				$episodeinfo = trim(str_replace("&nbsp;"," ",$episodeinfo));
			}
			$screenshot  = substr($episodepage, strpos($episodepage, "http://images.tvrage.net/screencaps/"));
			$screenshot  = substr($screenshot, 0, strpos($screenshot, "\""));
			$screenshot  = strip_tags($screenshot);

			$publisher = trim($temp[11]);



			$movie = '"'.trim($temp[0]).'"';
			if($oldmovie != $movie){
				echo "Opening series ".$movie."\n";
				if(isset($argv[3])){
					$imdbnr = $argv[3];
				}else{
					$test = file("http://movies.tegosaurus.com/title2imdbnr.php?t=".urlencode($movie));
					$imdbnr = $test[0];
				}
				if($imdbnr > 0){ 
					echo "IMDB: ".$imdbnr."\n"; 
					$tvxml = implode("",file("http://movies.tegosaurus.com/atvfilesimdbtvxml.php?id=".$imdbnr));
				}else{ 
					$tvxml = ""; 
					echo("No IMDB number found...\n\n"); 
				}
			}else{
				echo "Still working in series ".$movie."\n";
			}
			$oldmovie = $movie;

			if($dir != $olddir){
				if(!file_exists($dir."/cover.jpg")){
//					$cover = file("http://movies.tegosaurus.com/images/".$imdbnr.".jpg");
//					$h = fopen($dir."/cover.jpg","w");
//					fwrite($h, implode("",$cover));
				}
			}
			$olddir = $dir;

			$xml = '<media type="TV Show">
	<title>'.sprintf("%02s",$episode).". ".$title.'</title>
	<description>'.str_replace("\n\n","\n",$episodeinfo).'</description>
	<publisher>'.$publisher.'</publisher>
	<copyright>Copyright '.trim($temp[2]).' '.$publisher.'</copyright>
	<seriesName>'.trim($temp[0]).'</seriesName>
	<broadcaster>'.$publisher.'</broadcaster>
	<episodeNumber>'.$season.$episode.'</episodeNumber>
	<episode>'.$episode.'</episode>
	<season>'.$season.'</season>
	<published>'.$airdate.'</published>
'.$tvxml.'
</media>
';
		
		/*
	<acquired>2007-04-01</acquired>
			<artist>October Road</artist>
			<summary>The Pros and Cons of Upsetting the Applecart</summary>
			<starRating>5</starRating>
		*/
		
			// Writing XML
			if(!file_exists($dir.str_replace(".".$ext,".xml", $file))){
				$h = fopen($dir.str_replace(".".$ext,".xml", $file),"w");
				fwrite($h, $xml);
				fclose($h);
			}

			// Getting screenshot for episode... Getting them online, or create them ourselves...
			if((!file_exists($dir.str_replace(".".$ext,".jpg", $file))) and (!file_exists($dir.str_replace(".".$ext,".png", $file)))){
				if(substr($screenshot, 0, 4) == "http"){
					$temp = implode("",file($screenshot));
					$h = fopen($dir.str_replace(".".$ext,".jpg",$file),"w");
					fwrite($h, $temp);
					fclose($h);
				}else{
					echo "Gonna have to make a screenshot...\n";
					// Make screenshot...
					if(file_exists($argv[2]."Contents/Resources/mplayer")){
						exec($argv[2].'Contents/Resources/mplayer -really-quiet -nosound -ss 720 -frames 1 -vf scale=400:-2 -vo png:z=1 "'.$dir.$file.'"');
						if(file_exists("00000001.png")){
							rename("00000001.png",$dir.str_replace(".".$ext,".png", $file));
						}
					}
				
				}
			}
		}
	}
	exit;



function get_show($show,$exact="",$episode="") {

if ( !$show ) { return FALSE; }

if ( $fp = fopen("http://www.tvrage.com/quickinfo.php?show=".urlencode($show)."&ep=".urlencode($episode)."&exact=".urlencode($exact),"r") )
  {
  while ( !feof($fp))
    {
    $line = fgets($fp,1024);
    list ($sec,$val) = explode('@',$line,2);
    if ($sec == "Show Name" )
      {
      $ret[0] = $val;
      }
    elseif ( $sec == "Show URL" )
      {
      $ret[1] = $val;
      }
    elseif ( $sec == "Premiered" )
      {
      $ret[2] = $val;
      }
    elseif ($sec == "Country" )
      {
      $ret[7] = $val;
      }
    elseif ( $sec == "Status" )
      {
      $ret[8] = $val;
      }
    elseif ( $sec == "Classification" )
      {
      $ret[9] = $val;
      }
    elseif ( $sec == "Genres" )
      {
      $ret[10] = $val;
      }
    elseif ( $sec == "Network" )
      {
      $ret[11] = $val;
      }
    elseif ( $sec == "Airtime" )
      {
      $ret[12] = $val;
      }

    elseif ( $sec == "Latest Episode" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[3] = $ep.", \"".$title."\" aired on ".$airdate;
      }
    elseif ( $sec == "Next Episode" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[4] = $ep.", \"".$title."\" airs on ".$airdate;
      }
    elseif ( $sec == "Episode Info" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[5] = $ep.", \"".$title."\" aired on ".$airdate;
      }
    elseif ( $sec == "Episode URL" )
      {
      $ret[6] = $val;
      }
    }
  fclose($fp);
  if ( $ret[0] )
    {
    return $ret;
    }
  }
else
  {
  return FALSE;
  }
}


?>
